package com.itheima.filter;

import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.util.StringUtils;

import java.io.IOException;

@Slf4j
@WebFilter(urlPatterns = "/*")
public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //获取登录路径，登录的请求要放行
        String uri = request.getRequestURI();
        if(uri.endsWith("/login")||uri.endsWith("/index")){
            filterChain.doFilter(request,response);
            return;
        }
        //获取请求头中的token
        String token = request.getHeader("token");
        // 判断 是否空，返回401
        if(StringUtils.hasLength(token)){
            //有token
            try {
                Claims claims = JwtUtils.parseJWT(token);
                filterChain.doFilter(request,response);
                return;
            } catch (Exception e) {
                log.error("解析token失败", e);
            }
        }
        response.setStatus(HttpStatus.SC_UNAUTHORIZED);
    }
}
